package com.xzy.shop.dao.impl;

import com.xzy.shop.dao.GoodsDao;
import com.xzy.shop.domain.Goods;
import com.xzy.shop.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Goods> findAll() {
        String sql = "select * from goods";
        return template.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class));
    }

    @Override
    public Goods findByGid(String gid) {
        String sql = "select * from goods where gid = ?";
        Goods goods = template.queryForObject(sql, new BeanPropertyRowMapper<Goods>(Goods.class), gid);
        return goods;
    }

    @Override
    public List<Goods> findByCid(String cid) {
        String sql = "select * from goods where cid = ?";
        return template.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class), cid);
    }

    @Override
    public List<Goods> serchGoods(String keywords) {
        String sql = "select * from goods where 1=1 ";
        StringBuilder sb = new StringBuilder(sql);
        List params = new ArrayList();

        if (keywords != null && keywords.length() > 0) {
            sb.append(" and `name` like ? ");
            params.add("%" + keywords + "%");
        }

        sql = sb.toString();
        return template.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class), params.toArray());
    }
}
